var macaddess = '';
var myFun = null;
var voltage = 0; // 版本比较

function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    const len = Math.max(v1.length, v2.length);

    while (v1.length < len) {
        v1.push('0');
    }

    while (v2.length < len) {
        v2.push('0');
    }

    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);

        if (num1 > num2) {
            return 1;
        } else {
            if (num1 < num2) {
                return -1;
            }
        }
    }

    return 0;
} //开始开门-处理函数 key:钥匙  fun：成功回调

function bindViewTap(key, fun) {
    if (fun) {
        myFun = fun;
    }

    macaddess = key.toUpperCase().replace(/\s+/g, ''); //检查蓝牙是否已经打开

    uni.getBluetoothAdapterState({
        success: function (res) {
            //手机蓝牙没打开
            if (!res.available) {
                uni.getSystemInfo({
                    success: function (res) {
                        if (res.platform.toUpperCase() == 'IOS') {
                            //如果是IOS
                            //判断微信版本是否支持
                            const version = uni.getSystemInfoSync().SDKVersion;

                            if (compareVersion(version, '2.13.1') >= 0) {
                                uni.showToast({
                                    title: '请开启蓝牙功能后再尝试开门',
                                    icon: 'none',
                                    duration: 3000
                                });
                            } else {
                                uni.showModal({
                                    title: '提示',
                                    content: '系统检测到您的微信版本过低，有可能会导致无法开门，请升级至微信最新版本。'
                                });
                            }
                        } else {
                            //安卓不判断版本
                            uni.showToast({
                                title: '请开启蓝牙功能后再尝试开门',
                                icon: 'none',
                                duration: 3000
                            });
                        }
                    }
                });
            } else {
                uni.showToast({
                    title: '正在开门',
                    icon: 'none',
                    mask: true,
                    duration: 15000
                });
                getBluetoothDevices();
            }
        },
        fail: function (res) {
            console.log(res);
            errHandle(res);
        }
    });
}

function getBluetoothDevices() {
    //获取搜索到的附近蓝牙设备
    uni.getBluetoothDevices({
        success: function (devices) {
            var i = 0;
            var mac = macaddess;

            for (i = 0; i < devices.devices.length; i++) {
                var advdat = ab2hex(devices.devices[i].advertisData);

                if (advdat.length < 12) {
                    continue;
                }

                advdat = advdat.substr(advdat.length - 12, 12);
                advdat = advdat.toUpperCase(); //如果广播的数据后面12位和设定的蓝牙号一样，就是我们要操作的锁

                if (advdat == mac) {
                    break;
                }
            }

            if (i < devices.devices.length) {
                //手机搜索到了设备
                var deviceid = devices.devices[i]['deviceId'];
                createBLEConnection(deviceid);
                console.log('搜索后连：');
            } else {
                //手机没搜索到设备，
                uni.getSystemInfo({
                    success: function (res) {
                        var androidid =
                            mac.substr(0, 2) + ':' + mac.substr(2, 2) + ':' + mac.substr(4, 2) + ':' + mac.substr(6, 2) + ':' + mac.substr(8, 2) + ':' + mac.substr(10, 2);

                        if (res.platform.toUpperCase() != 'IOS') {
                            //某些安卓手机就是搜索不到设备，则尝试直接连接，连接的　参数是ＭＡＣ加冒号隔开如　38:45:DC:54:54:10
                            createBLEConnection(androidid);
                            console.log('直接连');
                        } else {
                            //ios不支持直接连接
                            uni.showToast({
                                title: '没搜索到设备,请重启蓝牙再试。',
                                icon: 'none',
                                duration: 3000
                            });
                        }
                    }
                });
            }
        },
        fali: function (res) {
            console.log(res);
            errHandle(res);
        }
    });
} //失败异常处理

function errHandle(res) {
    if (res.errCode == 10000) {
        openBluetoothAdapter();
        uni.showToast({
            title: '正在初始化蓝牙适配器，请稍后再试。',
            icon: 'none'
        });
    } else {
        if (res.errCode == 10001) {
            uni.showToast({
                title: '当前蓝牙适配器不可用',
                icon: 'none'
            });
        } else {
            if (res.errCode == 10002) {
                uni.showToast({
                    title: '没有找到指定设备，请到达房间门口再试',
                    icon: 'none'
                });
            } else {
                if (res.errCode == 10003) {
                    uni.showToast({
                        title: '连接失败',
                        icon: 'none'
                    });
                } else {
                    if (res.errCode == 10004) {
                        uni.showToast({
                            title: '没有找到指定服务',
                            icon: 'none'
                        });
                    } else {
                        if (res.errCode == 10005) {
                            uni.showToast({
                                title: '没有找到指定特征值',
                                icon: 'none'
                            });
                        } else {
                            if (res.errCode == 10006) {
                                uni.showToast({
                                    title: '当前连接已断开',
                                    icon: 'none'
                                });
                            } else {
                                if (res.errCode == 10007) {
                                    uni.showToast({
                                        title: '当前特征值不支持此操作',
                                        icon: 'none'
                                    });
                                } else {
                                    if (res.errCode == 10008) {
                                        uni.showToast({
                                            title: '系统不支持',
                                            icon: 'none'
                                        });
                                    } else {
                                        if (res.errCode == 10009) {
                                            uni.showToast({
                                                title: 'Android 系统特有，系统版本低于 4.3 不支持 BLE',
                                                icon: 'none'
                                            });
                                        } else {
                                            if (res.errCode == 10012) {
                                                uni.showToast({
                                                    title: '连接超时',
                                                    icon: 'none'
                                                });
                                            } else {
                                                if (res.errCode == 10013) {
                                                    uni.showToast({
                                                        title: '连接 deviceId 为空或者是格式不正确',
                                                        icon: 'none'
                                                    });
                                                } else {
                                                    uni.showToast({
                                                        title: res.errMsg,
                                                        icon: 'none'
                                                    });
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

function init() {
    openBluetoothAdapter();
}

function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
        return ('00' + bit.toString(16)).slice(-2);
    });
    return hexArr.join('');
} //开启蓝牙搜索功能

function startBluetoothDevicesDiscovery() {
    uni.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: false,
        interval: 4000,
        //4秒上报一次
        success: function (res) {},
        fali: function (res) {
            console.log(res);
            stopBluetoothDevicesDiscovery(); //关闭蓝牙搜索功能
        }
    });
} //关闭蓝牙搜索功能

function stopBluetoothDevicesDiscovery() {
    uni.stopBluetoothDevicesDiscovery({
        //一旦检测到设备马上关闭叟索功能
        success: function (res) {},
        fali: function (res) {
            console.log(res);
        }
    });
} //打开蓝牙库

function openBluetoothAdapter() {
    uni.openBluetoothAdapter({
        // 手机蓝牙已打开会执行success函数
        success: function (res) {
            setTimeout(function () {
                startBluetoothDevicesDiscovery(); //手机蓝牙已打开，开启搜索
            }, 200);
        },
        fail: function (res) {
            //手机蓝牙不打开会执行fail函数
            console.log(res);
        },
        complete: function (res) {
            //如果手机蓝牙没打开，开始蓝控手机蓝牙状态，只要一打开。就会执行搜索
            uni.onBluetoothAdapterStateChange(function (res) {
                if (res.available && !res.discovering) {
                    uni.showToast({
                        title: '蓝牙正在启动请稍后再试...',
                        icon: 'none',
                        mask: true,
                        duration: 3000
                    });
                    setTimeout(function () {
                        startBluetoothDevicesDiscovery(); //手机蓝牙开了，开始搜索设备
                    }, 200);
                }
            });
        }
    });
} //关闭蓝牙库

function closeBluetoothAdapter() {
    uni.closeBluetoothAdapter({
        success: function (res) {
            console.log('closeBluetoothAdapter.ok');
        },
        fail: function (res) {
            console.log(res);
        }
    });
} //链接附近蓝牙设备

function createBLEConnection(condeviceid) {
    uni.createBLEConnection({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: condeviceid,
        success: function (res) {
            console.log('连接成功');
            setTimeout(function () {
                getService(condeviceid); //获取服务
            }, 500);
        },
        fail: function (res) {
            console.log(res);
            uni.showToast({
                title: '门锁连接失败，请在3秒后重试！',
                icon: 'none',
                duration: 3000
            });
        }
    });
} //获取设备的所有服务

function getService(readdeviceId) {
    // 监听蓝牙连接
    // 获取蓝牙设备service值
    uni.getBLEDeviceServices({
        deviceId: readdeviceId,
        success: function (res) {
            console.log('获取设备服务成功');
            setTimeout(function () {
                var index;

                for (index = 0; index < 4; index++) {
                    if (res.services[index]['uuid'].indexOf('FEE9') >= 0) {
                        break;
                    }
                }

                if (index >= 4) {
                    closeBLEConnection(readdeviceId); //关闭连接服务
                } else {
                    getBLEDeviceCharacteristics(readdeviceId, res.services[index]['uuid']); //获取特征值
                }
            }, 500); //某些安卓机需等待0.3秒
        },
        fail: function (res) {
            uni.showToast({
                title: '获取设备服务故障',
                icon: 'none',
                duration: 3000
            });
            closeBLEConnection(readdeviceId); //关闭连接服务
        }
    });
} //读取特征值

function getBLEDeviceCharacteristics(readdeviceId, readservicesid) {
    uni.getBLEDeviceCharacteristics({
        deviceId: readdeviceId,
        serviceId: readservicesid,
        success: function (res) {
            let item = res.characteristics[0];

            if (item.properties.read) {
                uni.readBLECharacteristicValue({
                    deviceId: readdeviceId,
                    serviceId: readservicesid,
                    characteristicId: item.uuid,

                    success(res) {
                        console.log(res);
                    },

                    fail(err) {
                        console.log(err);
                    }
                });
            }

            setTimeout(function () {
                writeBLECharacteristicValue(readdeviceId, readservicesid, res.characteristics[1]['uuid']);
            }, 300); //某些安卓机需等待0.3秒
        },
        fail: function (res) {
            errHandle(res);
            closeBLEConnection(readdeviceId); //关闭连接服务
        }
    }); // 操作之前先监听，保证第一时间获取数据

    uni.onBLECharacteristicValueChange((characteristic) => {
        console.log('16:' + ab2hex(characteristic.value));
        console.log('10:' + parseInt(ab2hex(characteristic.value), 16));
        voltage = parseInt(ab2hex(characteristic.value), 16);
    });
} //传数据给蓝牙

function writeBLECharacteristicValue(readdeviceId, readservicesid, characteristicsid) {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(20);
    let dataView = new DataView(buffer);
    var arr = [];

    for (var i = 0; i < macaddess.length; i = i + 2) {
        arr.push('0x' + macaddess.substring(i, i + 2));
    }

    dataView.setUint8(0, '0x' + (arr[0] ^ arr[1]).toString(16));
    dataView.setUint8(1, '0x' + (arr[1] ^ arr[2]).toString(16));
    dataView.setUint8(2, '0x' + (arr[2] ^ arr[3]).toString(16));
    dataView.setUint8(3, '0x' + (arr[3] ^ arr[4]).toString(16));
    dataView.setUint8(4, '0x' + (arr[4] ^ arr[5]).toString(16));
    dataView.setUint8(5, '0x' + (arr[5] ^ arr[0]).toString(16));
    uni.writeBLECharacteristicValue({
        // 这里的 deviceId 需要在上面的 getBluetoothDevice 或 onBluetoothDeviceFound 接口中获取
        deviceId: readdeviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        serviceId: readservicesid,
        // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
        characteristicId: characteristicsid,
        // 这里的value是ArrayBuffer类型
        value: buffer,
        success: function (res) {
            uni.showToast({
                title: '已解锁',
                icon: 'success',
                duration: 3000
            });
            console.log(res);

            if (myFun != null) {
                myFun(voltage);
            }
        },
        fail: function (res) {
            console.log(res);
        },
        complete: function (res) {
            closeBLEConnection(readdeviceId); //关闭连接服务
        }
    });
} //断开蓝牙设备

function closeBLEConnection(condeviceid) {
    uni.closeBLEConnection({
        deviceId: condeviceid,
        success: function (res) {
            console.log(res);
        },
        fail: function (res) {
            console.log(res);
        }
    });
}

module.exports = {
    bindViewTap: bindViewTap,
    init: init
};
